<template>
  <div class="system-user-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="system-user-search mb15">
        <el-row :gutter="20">
          <el-col :span="2" class="mb15">
            <el-input size="large" placeholder="请输入应用名称" v-model="appName" style="max-width: 240px"></el-input>
          </el-col>
          <el-col :span="4" class="mb15">
            <el-tree-select
                placeholder="请选择学校"
                v-model="searchState.orgId"
                :data="searchState.sysOrgData"
                :render-after-expand="false"
                style="width: 200px"
                check-strictly
                filterable
                show-all-levels
                multiple
            />
          </el-col>
          <el-col :span="4" class="mb15">
            <el-tree-select
                placeholder="请选择教育局"
                v-model="searchState.areaOrgId"
                :data="searchState.areaOrgData"
                :render-after-expand="false"
                style="width: 200px"
                check-strictly
                filterable
                show-all-levels
                multiple
            />
          </el-col>
          <el-col :span="4" class="mb15">
            <el-select v-model="searchState.appCategory"
                       placeholder="请选择应用分类"
                       clearable
                       class="w100">
              <el-option
                  v-for="item in searchState.appCategoryOptions"
                  :key="item.key"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="4" class="mb15">
            <el-select v-model="searchState.appSuitCrowds" placeholder="请选择应用适用人群"
                       multiple clearable class="w100">
              <el-option
                  v-for="item in searchState.appSuitCrowdOptions"
                  :key="item.key"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6" class="mb15">
            <el-button size="large" type="primary" class="ml10" @click="getTableData">
              <el-icon>
                <ele-Search/>
              </el-icon>
              查询
            </el-button>
            <el-button size="large" type="success" class="ml10" @click="onOpenAdd('add')">
              <el-icon>
                <ele-FolderAdd/>
              </el-icon>
              创建应用
            </el-button>
          </el-col>
        </el-row>

      </div>
      <el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%">
        <el-table-column type="index" label="序号" width="80"/>
        <el-table-column prop="appName" label="应用名称" show-overflow-tooltip width="150"></el-table-column>
        <el-table-column prop="appShortName" label="应用简称" show-overflow-tooltip width="150"></el-table-column>
        <el-table-column prop="appLogo" label="应用logo" show-overflow-tooltip width="130">
          <template #default="scope">
            <el-image
                style="width: 40px; height: 40px"
                :src="scope.row.appLogo"
                :preview-src-list="[scope.row.appLogo]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="appTerminal" label="应用终端" show-overflow-tooltip width="130">
          <template #default="scope">
            <p v-for="terminal in scope.row.appTerminal" :key="terminal">
              {{ getTerminalLabel(terminal) }}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="appCategory" label="应用分类" show-overflow-tooltip width="130">
          <template #default="scope">
            <div v-if="scope.row.appCategory==1">教育教学</div>
            <div v-if="scope.row.appCategory==2">教育管理</div>
            <div v-if="scope.row.appCategory==3">教育评价</div>
            <div v-if="scope.row.appCategory==4">教育服务</div>
            <div v-if="scope.row.appCategory==0" style="color: red">尚未选择</div>
          </template>
        </el-table-column>
        <el-table-column prop="appStatus" label="应用状态" show-overflow-tooltip width="130">
          <template #default="scope">
            <el-tag type="" color="yellow" v-if="scope.row.appStatus==0">初始提交审核</el-tag>
            <el-tag type="" color="green" v-if="scope.row.appStatus==1">api调试中</el-tag>
            <el-tag type="" color="red" v-if="scope.row.appStatus==2">申请上线中</el-tag>
            <el-tag type="info" v-if="scope.row.appStatus==3">申请上线未通过</el-tag>
            <el-tag type="success" v-if="scope.row.appStatus==4">已上线</el-tag>
            <el-tag type="warning" v-if="scope.row.appStatus==5">申请下线</el-tag>
            <el-tag type="danger" v-if="scope.row.appStatus==6">已下线</el-tag>
            <el-tag type="danger" v-if="scope.row.appStatus==7">已下线</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reviewStatus" label="审核状态" show-overflow-tooltip width="130">
          <template #default="scope">
            <div v-if="scope.row.reviewStatus==0">待审核</div>
            <div v-if="scope.row.reviewStatus==1">通过</div>
            <div v-if="scope.row.reviewStatus==2">拒绝</div>
          </template>
        </el-table-column>
        <el-table-column prop="gmtCreate" label="创建时间" show-overflow-tooltip width="130">
          <template #default="scope">
            <div style="font-size: 12px">
              {{ scope.row.gmtCreate }}
            </div>
          </template>
        </el-table-column>
        <!--        <el-table-column prop="priorityNum" label="排序序号" show-overflow-tooltip width="130">-->
        <!--          <template #default="scope">-->
        <!--            <div style="font-size: 12px">-->
        <!--              {{ scope.row.priorityNum }}-->
        <!--            </div>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="操作" width="350">
          <template #default="scope">
            <el-button :disabled="scope.row.userName === 'admin'" size="small" type="primary"
                       @click="onOpenEdit('edit', scope.row)">修改
            </el-button>

            <el-button v-show="scope.row.appStatus==4" size="small" type="danger"
                       @click="onLineOffline(scope.row, 7)">下线
            </el-button>

            <el-button v-show="scope.row.appStatus==7" size="small" type="primary"
                       @click="onLineOffline(scope.row, 4)">上线
            </el-button>

            <el-button size="small" type="primary"
                       @click="seeAppKey('edit', scope.row)">查看应用秘钥
            </el-button>

            <el-button size="small" type="danger"
                       @click="onRowDel(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="onHandleSizeChange"
          @current-change="onHandleCurrentChange"
          class="mt15"
          :pager-count="5"
          :page-sizes="[100, 200, 500]"
          v-model:current-page="state.tableData.param.pageNum"
          background
          v-model:page-size="state.tableData.param.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="state.tableData.total"
      >
      </el-pagination>
    </el-card>
    <AppsDialog ref="appsDialogRef"
                @refresh="getTableData()"
                :orgTree="searchState.sysOrgData"
                :areaOrgTree="searchState.areaOrgData"
                :interfaceOptions="searchState.interfaceOptions"
    />
    <AppKeyDialog ref="appKeyDialogFormRef"/>

  </div>
</template>

<script setup lang="ts" name="apps">
import {defineAsyncComponent, reactive, onMounted, ref} from 'vue';
import {ElMessageBox, ElMessage} from 'element-plus';
import {useAppsApi} from '/@/api/apps'

const {listByAppPage, removeById, applyAppOnLineOffline} = useAppsApi();
import {systemApi} from "/@/api/system";

const {orgAreaTree, orgBOETree} = systemApi();


import {useInterfacesApi} from '/@/api/interfaces'

const {list} = useInterfacesApi();

// 引入组件
const AppsDialog = defineAsyncComponent(() => import('/src/views/app/dialog.vue'));
const AppKeyDialog = defineAsyncComponent(() => import('/src/views/app/appKeyDialog.vue'));
const appName = ref('');
// 定义变量内容
const appsDialogRef = ref();
const appKeyDialogFormRef = ref();
const state = reactive<AppsState>({
  tableData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 100,
    },
  }
});

const searchState = ref({
  orgId: '',
  areaOrgId: '',
  appSuitCrowds: [],
  sysOrgData: [] as OrgTreeType[],
  areaOrgData: [] as OrgTreeType[],
  appSuitCrowdOptions: [
    // {value: '0', key: '0', label: '不限'},
    {value: 'student', key: '1', label: '学生'},
    {value: 'teacher', key: '2', label: '普通教师'},
    {value: 'teacherManager', key: '3', label: '教师管理员'},
    {value: 'parent', key: '4', label: '家长'},
    {value: 'leader', key: '5', label: '教育局管理员'},
    {value: 'schoolManager', key: '6', label: '学校管理员'},
    {value: 'BOELeader', key: '7', label: 'BOE-教育局领导'},
    {value: 'BOEDepartmentHead', key: '8', label: 'BOE-部门负责人'},
    {value: 'BOEDepartmentStaff', key: '9', label: 'BOE-部门工作人员'},
    {value: 'BOESchoolHead', key: '10', label: 'BOE-校长'},
    {value: 'BOESchoolDirector', key: '11', label: 'BOE-办公室主任'},
  ],
  appTerminalOptions: [
    {value: '1', key: '1', label: 'web端'},
    {value: '2', key: '2', label: '手机APP'},
    {value: '3', key: '3', label: 'H5'},
  ],
  appCategory: [],
  appCategoryOptions: [
    {value: '1', key: '1', label: '教育教学'},
    {value: '2', key: '2', label: '教育管理'},
    {value: '3', key: '3', label: '教育评价'},
    {value: '4', key: '4', label: '教育服务'},
  ],
  interfaceOptions: []
})

// 加载学校树数据
const loadSchoolOrgTreeData = async () => {
  state.tableData.loading = true;
  searchState.value.sysOrgData = [];
  const res = await orgBOETree()
  if (res.status === 200) {
    searchState.value.sysOrgData = res.data;
    state.tableData.loading = false;
  }
};

// 加载三方应用接口列表
const loadInterfaceList = async () => {
  searchState.value.interfaceOptions = [];
  const res = await list();
  if (res.status === 200) {
    searchState.value.interfaceOptions = res.data;
  }
};

// 加载区域树
const loadOrgTreeData = async () => {
  state.tableData.loading = true;
  searchState.value.areaOrgData = [];
  const res = await orgAreaTree()
  if (res.status === 200) {
    searchState.value.areaOrgData = res.data;
    state.tableData.loading = false;
  }
};

// 初始化表格数据
const getTableData = async () => {
  state.tableData.loading = true;
  const data = [];
  const res = await listByAppPage({
    current: state.tableData.param.pageNum,
    pageSize: state.tableData.param.pageSize,
    appName: appName.value,
    // 学校id
    orgId: searchState.value.orgId,
    areaOrgId: searchState.value.areaOrgId,
    appSuitCrowds: searchState.value.appSuitCrowds,
    appCategory: searchState.value.appCategory,
  });
  if (res.status === 200) {
    res.data.records.forEach((item: any) => {
      if (item.appSuitCrowds) {
        item.appSuitCrowds = item.appSuitCrowds.split(',');
      }
      if (item.orgId) {
        item.orgId = item.orgId.split(',');
      }
      if (item.areaOrgIds) {
        item.areaOrgIds = item.areaOrgIds.split(',');
      }
      if (item.appTerminal) {
        item.appTerminal = item.appTerminal.split(',');
      }
    })
    data.push(...res.data.records);
    // console.log('最终结果为', data)
  }
  state.tableData.data = data;
  state.tableData.total = res.data.total;
  state.tableData.loading = false;
};
// 打开新增弹窗
const onOpenAdd = (type: string) => {
  appsDialogRef.value.openDialog(type);
};
// 打开修改弹窗
const onOpenEdit = (type: string, row: RowAppsType) => {
  appsDialogRef.value.openDialog(type, row);
};

const seeAppKey = (type: string, row: RowAppsType) => {
  appKeyDialogFormRef.value.openDialog(type, row);
};

const onLineOffline = async (row: RowAppsType, status: number) => {
  ElMessageBox.confirm(`确定要 ${status == 4 ? '上架' : '下架'} 名为：“${row.appName}的应用吗？”，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await applyAppOnLineOffline({id: row.id, appStatus: status})
    if (res.status === 200) {
      await getTableData();
      ElMessage.success('操作成功');
    }
  }).catch(() => {
  });
};

// 删除
const onRowDel = (row: RowAppsType) => {
  ElMessageBox.confirm(`确定要删除名为：“${row.appName}的应用吗？”，是否继续?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await removeById({id: row.id})
    if (res.status === 200) {
      await getTableData();
      ElMessage.success('删除成功');
    }
  }).catch(() => {
  });
};

// 分页改变
const onHandleSizeChange = (val: number) => {
  state.tableData.param.pageSize = val;
  getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
  state.tableData.param.pageNum = val;
  getTableData();
};
// 页面加载时
onMounted(() => {
  loadInterfaceList();
  loadOrgTreeData();
  loadSchoolOrgTreeData();
  getTableData();
});

// 获取终端标签类型
const getTagType = (terminal: string) => {
  switch (terminal) {
    case '1':
      return 'success';
    case '2':
      return 'warning';
    case '3':
      return 'danger';
    default:
      return '';
  }
};

// 获取终端标签文本
const getTerminalLabel = (terminal: string) => {
  switch (terminal) {
    case '1':
      return 'web';
    case '2':
      return '小程序';
    case '3':
      return 'H5';
    default:
      return '';
  }
};

</script>

<style scoped lang="scss">
.system-user-container {
  :deep(.el-card__body) {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: auto;

    .el-table {
      flex: 1;
    }
  }
}
</style>
